package com.example.controller;

import com.example.entity.ServiceApplication;
import com.example.entity.User;
import com.example.service.ServiceApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * 服务申请控制器，处理服务申请的提交、状态查看和文件下载等请求
 */
@Controller
@RequestMapping("/application")
public class ApplicationController {
    // 自动注入服务申请服务
    @Autowired
    private ServiceApplicationService applicationService;

    // 上传文件的目录
    private static final String UPLOAD_DIR = "uploads/documents/";

    /**
     * 显示服务申请表单页面
     * @param model 用于向视图传递数据
     * @return 服务申请表单页面路径
     */
    @GetMapping("/submit")
    public String showApplicationForm(Model model) {
        // 创建一个新的服务申请对象并添加到模型中
        model.addAttribute("application", new ServiceApplication());
        return "application/submit";
    }

    /**
     * 提交服务申请
     * @param application 服务申请对象
     * @param file 上传的文件
     * @param session Http会话，用于获取当前用户信息
     * @return 重定向的页面路径
     * @throws IOException 输入输出异常
     */
    @PostMapping("/submit")
    public String submitApplication(
            @ModelAttribute ServiceApplication application,
            @RequestParam("document") MultipartFile file,
            HttpSession session) throws IOException {

        // 从session获取当前用户信息
        User user = (User) session.getAttribute("login_user");

        // 检查用户是否登录，如果未登录则重定向到登录页
        if (user == null) {
            return "redirect:/user/login";
        }

        // 保存上传的文件
        if (!file.isEmpty()) {
            // 获取上传目录的路径
            Path uploadPath = Paths.get(UPLOAD_DIR);

            // 如果上传目录不存在，则创建目录
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成文件名
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            Path filePath = uploadPath.resolve(fileName);

            // 将文件保存到指定路径
            file.transferTo(filePath.toFile());

            // 设置服务申请对象的文件路径
            application.setDocument_path(filePath.toString());
        }

        // 设置服务申请对象的用户ID
        application.setUser_id(user.getUser_id());

        // 调用服务提交申请
        applicationService.submitApplication(application);

        // 重定向到申请状态页面
        return "redirect:/application/status";
    }

    /**
     * 查看服务申请状态
     * @param session Http会话，用于获取当前用户信息
     * @param model 用于向视图传递数据
     * @return 服务申请状态页面路径
     */
    @GetMapping("/status")
    public String viewApplicationStatus(HttpSession session, Model model) {
        // 从session获取当前用户信息
        User user = (User) session.getAttribute("login_user");

        // 检查用户是否登录，如果未登录则重定向到登录页
        if (user == null) {
            return "redirect:/user/login";
        }

        // 调用服务获取用户的服务申请列表
        List<ServiceApplication> applications = applicationService.getUserApplications(user.getUser_id());

        // 将服务申请列表添加到模型中，以便在视图中显示
        model.addAttribute("applications", applications);

        return "application/status";
    }

    /**
     * 下载服务申请的文件
     * @param applicationId 服务申请的ID
     * @param request Http请求
     * @param response Http响应，用于返回文件
     * @throws IOException 输入输出异常
     */
    @GetMapping("/download/{applicationId}")
    public void downloadDocument(@PathVariable Integer applicationId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 根据申请ID获取服务申请信息
        ServiceApplication application = applicationService.getApplicationById(applicationId);

        if (application != null && application.getDocument_path() != null) {
            // 获取文件路径
            String filePath = application.getDocument_path();
            File file = new File(filePath);

            if (file.exists()) {
                // 设置响应头，指定文件下载
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
                response.setContentLength((int) file.length());

                // 读取文件并输出到响应流
                try (FileInputStream fis = new FileInputStream(file);
                     OutputStream os = response.getOutputStream()) {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = fis.read(buffer)) != -1) {
                        os.write(buffer, 0, bytesRead);
                    }
                }
            }
        }
    }
}